package com.leaf.lowcode.service;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.leaf.lowcode.API.AppointmentApi;
import com.leaf.lowcode.entity.VisitBean;
import com.leaf.lowcode.entity.VisitorInfo;
import com.leaf.lowcode.entity.VistorRequest;
import com.leaf.lowcode.mapper.VisitorMapper;
import com.leaf.lowcode.utils.RsaUtil;
import com.leaf.lowcode.utils.jsontobean.JsonToBeanV;
import org.apache.commons.lang3.time.DateFormatUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.*;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;

import java.util.Base64;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;

@Component
public class AppointSertvice {
    @Autowired
    private VisitorMapper visitorMapper;
   // @Scheduled(initialDelay =  1000, fixedRate = 1000)
    public void execute() throws Exception {
        Date cur = new Date();
        Calendar calendar = new GregorianCalendar();
        calendar.add(Calendar.DAY_OF_MONTH,1);

//一天的开始时间 yyyy:MM:dd 00:00:00
        calendar.set(Calendar.HOUR_OF_DAY,0);
        calendar.set(Calendar.MINUTE,0);
        calendar.set(Calendar.SECOND,0);
        calendar.set(Calendar.MILLISECOND,0);
        Date dayStart = calendar.getTime();
        String pattern = "YYYY-MM-dd'T'HH:mm:ssZZ";
        String startStr = DateFormatUtils.format(dayStart,pattern);
        System.out.println("startStr"+startStr);

//一天的结束时间 yyyy:MM:dd 00:00:00
        calendar.set(Calendar.HOUR_OF_DAY,23);
        calendar.set(Calendar.MINUTE,59);
        calendar.set(Calendar.SECOND,59);
        calendar.set(Calendar.MILLISECOND,999);
        Date dayEnd = calendar.getTime();
        String endStr=DateFormatUtils.format(dayEnd,pattern);
        System.out.println("startStr"+endStr);

        QueryToken queryToken = new QueryToken();

        System.out.println("==================启动=================");

        //    public static void main(String[] args) throws Exception {

        String publicKey = new RsaUtil("rsapublic.xml").Key();

        //  System.out.println(publicKey);

        String msg=" {\n" +
                "            \"visitAppointedTimeStart\":\"2021-01-01\",\n" +
                "                \"visitAppointedTimeEnd\":\"2021-12-01\",\n" +
                "            \"visitorUserName\":\"\"\n" +
                "        }";

        EncrypRSA rsa = new EncrypRSA();

        byte[] ciphertextPublic = rsa.encrypt(publicKey, msg, "PUBLIC");

        String json = new String(Base64.getEncoder().encode(ciphertextPublic));

        //String cleartextPublic = rsa.decryptToString(publicKey,  new String(Base64.getEncoder().encode(ciphertextPrivate)),EncrypRSA.PUBLIC);

        RestTemplate restTemplate = new RestTemplate();

        HttpHeaders headers = new HttpHeaders();

        HttpMethod method = HttpMethod.POST;
        // 以表单的方式提交
        headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
        //添加参数developerId
        MultiValueMap<String, String> multiValueMap = new LinkedMultiValueMap<>();

       multiValueMap.add("json", json);
        //封装
        HttpEntity<MultiValueMap<String, String>> request = new HttpEntity<>(multiValueMap, headers);
        //post请求
        String token=queryToken.execute();

        System.out.println("token"+token);

        //System.out.println("token"+token);
        String url="https://work.spic.com.cn:8443/mgr/visitor/open/getRecord.do?token=";
//        String url="https://workuat.spic.com.cn/mgr/visitor/open/getRecord.do?token=";
        String urltoken=url+token;
        ResponseEntity<String> responseEntity = restTemplate.exchange(urltoken, method, request, String.class);
        //提交
        String body = responseEntity.getBody();
        System.out.println("body"+responseEntity.getBody());
        System.out.println(" Header"+ responseEntity.getHeaders());
        System.out.println("code"+responseEntity.getStatusCode());
        JSONObject jsonObject=JSONObject.parseObject(body);
        JSONArray vistiorlist= (JSONArray)((JSONObject) jsonObject.get("data")).get("data");
        VisitBean visitBean =new VisitBean();
        for(int i=0;i<vistiorlist.size();i++)
          {
              JSONObject vistiorJson = (JSONObject) vistiorlist.get(i);
              JsonToBeanV<VisitBean> jsonToBeanV = new JsonToBeanV<VisitBean>();
              visitBean = jsonToBeanV.tansfrom(visitBean, vistiorJson);
              VisitBean   flag  =visitorMapper.selectId(visitBean.getId());
              if (flag == null){
                  System.out.println("不存在");
                  visitorMapper.insert(visitBean);
                  AppointmentApi appointmentApi= new AppointmentApi();
                  VistorRequest  vistorRequest = new VistorRequest();
                  vistorRequest.setReceptionistId("f6436575d656415eac49aff1b37024fd");
                  vistorRequest.setPersonNum(1);
                  VisitorInfo visitorInfo = new VisitorInfo();
                  visitorInfo.setGender(1);
                  visitorInfo.setVisitorName(visitBean.getVisitorUserName());
                  visitorInfo.setPhoneNo(visitBean.getVisitorUserPhone());
                  visitorInfo.setCertificateNo(visitBean.getVisitorUserIdNumber());
                  visitorInfo.setCertificateType(111);
                  visitorInfo.setNation(1);
                  vistorRequest.setVisitStartTime(visitBean.getVisitAppointedTime());
                  vistorRequest.setVisitEndTime(endStr);
                  vistorRequest.setVisitorInfo(visitorInfo);
                  String re =appointmentApi.visitorAppointment(vistorRequest);
                  System.out.println("海康威视"+re);
              }else
              {
                  System.out.println("存在");
              }
          }
    }


}
